package com.kgc.crowd.distributioincrowdwebui.controller;

import com.kgc.crowd.distributioncrowdcommon.api.MemberManagerRemoteService;
import com.kgc.crowd.distributioncrowdcommon.api.ProjectManagerRemoteService;
import com.kgc.crowd.distributioncrowdcommon.pojo.MemberLaunchInfoPO;
import com.kgc.crowd.distributioncrowdcommon.pojo.ResultEntity;
import com.kgc.crowd.distributioncrowdcommon.pojo.TypePO;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdConstant;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdUtils;
import com.kgc.crowd.distributioncrowdcommon.util.UploadUtil;
import com.kgc.crowd.distributioncrowdcommon.vo.MemberSignSuccessVO;
import com.kgc.crowd.distributioncrowdcommon.vo.ProjectVO;
import com.kgc.crowd.distributioncrowdcommon.vo.TagVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 项目名：distribution-crowd-parent
 * 创建人：Junyizm
 * 创建时间：2020/4/13-10:30
 */
@Controller
@RequestMapping("/project/manager")
public class ProjectController {

    @Resource
    ProjectManagerRemoteService projectManagerRemoteService;

    @RequestMapping("/start")
    public String start(){
        return "start";
    }
    @Resource
    MemberManagerRemoteService memberManagerRemoteService;

    @RequestMapping("/agree/protocol")
    public String agreeProtocol(Model model, HttpSession session){
        //获取登录状态
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(obj == null){
            return "redirect:/to/login.html";
        }
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) obj;
        String token = memberSignSuccessVO.getToken();
        //加载分类信息
        ResultEntity<List<TypePO>> listResultEntity = projectManagerRemoteService.selectAllType();
        model.addAttribute(CrowdConstant.ATTR_NAME_TYPEPO_LIST,listResultEntity.getData());
        //加载标签信息
        ResultEntity<List<TagVO>> allTag = projectManagerRemoteService.selectAllTag();
        model.addAttribute(CrowdConstant.ATTR_NAME_TAG_LIST,allTag.getData());
        //回显发起人信息
        ResultEntity<MemberLaunchInfoPO> memberLaunchInfoPOResultEntity = memberManagerRemoteService.retrieveMemberLaunchInfoByMemberToken(token);
        model.addAttribute(CrowdConstant.ATTR_NAME_MEMBERLAUNCHINFO,memberLaunchInfoPOResultEntity.getData());
        //初始化projectVO
        ResultEntity<ProjectVO> projectVOResultEntity = projectManagerRemoteService.initCreation(token);
        if(projectVOResultEntity.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,projectVOResultEntity.getMessage());
            return "redirect:/project/manager/start";
        }
        //把projectVO存入Session
        session.setAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT,projectVOResultEntity.getData());
        return "start-step-1";
    }

    @Value("${endpoint}")
    private String endpoint;
    @Value("${accessKeyId}")
    private String accessKeyId;
    @Value("${accessKeySecret}")
    private String accessKeySecret;
    @Value("${headPicturefolderName}")
    private String headPicturefolderName;
    @Value("${bucketName}")
    private String bucketName;
    @Value("${domain}")
    private String domain;
    @Value("${detailPicturefolderName")
    private String detailPicturefolderName;

    @RequestMapping("/upload/head/picture")
    @ResponseBody
    public ResultEntity<String> ipload(MultipartFile headerPicture,HttpSession session) throws IOException {
        //验证是否登录
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(obj==null){
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) obj;
        String memberSignTken = memberSignSuccessVO.getToken();

        Object obj02 = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if(obj02==null){
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_NO_INITED_PROJECT);
        }
        ProjectVO projectVO = (ProjectVO) obj02;
        String projectTempToken = projectVO.getProjectTempToken();

        //验证是否选择文件
        if(headerPicture==null){
            ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }

        //获取旧的文件名
        String originalFilename = headerPicture.getOriginalFilename();
        //根据旧文件名生成新文件名
        String fileName = UploadUtil.generateFileName(originalFilename);
        //把文件对象转换成文件流
        InputStream inputStream = headerPicture.getInputStream();
        //文件上传
        UploadUtil.uploadSingleFile(inputStream,fileName,endpoint,accessKeyId,accessKeySecret,headPicturefolderName,bucketName);
        //保存头图路径到redis
        String headerPicturePath = domain+"/"+headPicturefolderName+"/"+fileName;
        projectManagerRemoteService.saveHeadPicturePath(memberSignTken,projectTempToken,headerPicturePath);
        return ResultEntity.successNoData();
    }


    @ResponseBody
    @RequestMapping("/upload/detail/picture")
    public ResultEntity<String> uploadDetailPicture(
            HttpSession session,
            @RequestParam("detailPicture") List<MultipartFile> detailPictureList
    ) throws IOException {

        // 登录检查
        MemberSignSuccessVO signVO = (MemberSignSuccessVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);

        if(signVO == null) {

            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }

        // 遍历用户上传的文件
        if(!CrowdUtils.collectionEffectiveCheck(detailPictureList)) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }

        List<String> detailPicturePathList = new ArrayList<>();

        for (MultipartFile detailPicture : detailPictureList) {
            boolean empty = detailPicture.isEmpty();

            if(empty) {
                continue ;
            }

            InputStream inputStream = detailPicture.getInputStream();

            String originalFileName = detailPicture.getOriginalFilename();

            String fileName = UploadUtil.generateFileName(originalFileName);

            UploadUtil.uploadSingleFile(inputStream,fileName,endpoint,accessKeyId,accessKeySecret,headPicturefolderName,bucketName);

            String detailPicturePath = domain + "/" + detailPicturefolderName + "/" + fileName;

            detailPicturePathList.add(detailPicturePath);
        }

        // 获取保存头图所需要的相关信息
        String memberSignToken = signVO.getToken();

        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);

        String projectTempToken = projectVO.getProjectTempToken();

        return projectManagerRemoteService.saveDetailPicturePathList(memberSignToken, projectTempToken, detailPicturePathList);

    }

}
